//
//  GZHomeController.swift
//  sinaweibo
//
//  Created by mac book pro on 16/3/20.
//  Copyright © 2016年 finish. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh
class GZHomeController: GZBaseTableViewController {
    /// 微博数据模型
    var statues: [GZStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if !GZUserAccountViewModel.sharedInstance.userLogin{ //登录后才能进行操作
            return
        }
        setNavigationBar()
        setNavigationTitle()
        prepareTableView()
    }
    func prepareTableView(){
        tableView.registerClass(GZStatusCell.self, forCellReuseIdentifier: "GZStatusCell")
        //根据autolayout自动布局
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        //去掉分割线
        tableView.separatorStyle = .None
        
        //添加下啦刷新控件
        tableView.addSubview(pullDownRefreshControl)
        pullDownRefreshControl.pullToRefreshHandler = {() -> () in
            self.loadNewData()
        }
        pullDownRefreshControl.beginRefreshing()
    }
    func loadMoreData(){
        let max_id = statues?.last?.id
        if max_id == 0{
            print("id为0不能上拉加载更多数据")
            return
        }
        //加载微博数据
        GZStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id!) { (statues, error) -> () in
            //停止动画
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil{
                SVProgressHUD.showErrorWithStatus("加载更多微博数据出错")
                return
            }
            self.statues = self.statues! + statues!
        }
    }
    func loadNewData(){
        let since_id = statues?.first?.id ?? 0
        GZStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { (statues, error) -> () in
            self.pullDownRefreshControl.endRefreshing() //结束刷新
            if error != nil{
                SVProgressHUD.showErrorWithStatus("加载微博数据失败,网络不给力", maskType: SVProgressHUDMaskType.Black)
                return
            }
            let count = statues?.count ?? 0
            if since_id > 0{
                self.showpullDowntip(statues!.count)
            }
            if count == 0{
                SVProgressHUD.showInfoWithStatus("没有新的微博数据")
                return
            }
            if since_id>0{//拼接数据
                self.statues = statues! + self.statues!
            }else{//刚进入程序
                self.statues = statues
                //添加上啦刷新
                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    self.loadMoreData()
                }
            }
        }
    }
    func showpullDowntip(count:Int){
        
        tipLabel.text =  count == 0 ? "没有微博数据" : "加载了 \(count) 条微博"
        UIView.animateWithDuration(defalutanimationDuration * 4, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(defalutanimationDuration, delay: 0.2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: { (_) -> Void in
                        
                })
        }
        
    }
    func setNavigationBar(){
        // 设置导航栏左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: "navigationbar_friendsearch_highlighted")
        
        // 设置导航栏右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: "navigationbar_pop_highlighted")
    }
    func setNavigationTitle(){
        // 设置导航栏标题
        let title = GZUserAccountViewModel.sharedInstance.userAccount?.screen_name
        let button = GZHomeTitleView(title: title!)
        button.addTarget(self, action: "didTitleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = button
        
    }
    func didTitleButtonClick(button:UIButton){
        button.selected = !button.selected
        if button.selected{ //选中
            UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                button.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI-0.0001))
            })
            
        }else{
            UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                button.imageView?.transform = CGAffineTransformIdentity
            })
        }
        
        //popoverView
        if button.selected {
            let popoverVC = GZPopoverViewController()
            //设置modal样式
            popoverVC.modalPresentationStyle = .Popover
            popoverVC.popoverPresentationController?.delegate = self
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            //设置popover显示大小
            popoverVC.preferredContentSize = CGSize(width: 200, height: 44 * popoverVC.titles.count)
            presentViewController(popoverVC, animated: true, completion: nil)
            
            
        }
        
        
    }
    
    //MARK : -lazy load
    private lazy var pullDownRefreshControl: GZPullDownRefreshControl =  GZPullDownRefreshControl()
    private lazy var tipLabel: UILabel = {
        let tipLabelHeight: CGFloat = 44
        
        let tipLabel = UILabel(frame: CGRectMake(0, -20 - tipLabelHeight, UIScreen.width, tipLabelHeight))
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        
        // 导航栏的frame = (0 20; 375 44)
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        return tipLabel
        }()
    
}
extension GZHomeController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //        return self.statues?.count ?? 0  //当statues为nil 时候 0
        return self.statues?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("GZStatusCell", forIndexPath: indexPath) as! GZStatusCell
        cell.status = self.statues?[indexPath.row]
        return cell
    }
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    
}
extension GZHomeController : UIPopoverPresentationControllerDelegate{
    //不让popover适配iphone,默认适配全屏，不适配就是popover
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    //系统会询问我门是否需要关闭 popover
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        // 让箭头转下来
        let titleButton = navigationItem.titleView as! GZHomeTitleView
        didTitleButtonClick(titleButton)
        
        return true
    }
}